
#------------------------------------------------------------------------------
# Utility Function
#------------------------------------------------------------------------------
function u_fun(ce::CE_Economy_PInf, cc::Float64)
utility = (cc.^(1.0-ce.γ))/(1.0-ce.γ)
return utility
end
#------------------------------------------------------------------------------


#------------------------------------------------------------------------------
# Function to Maximize when Repayment
#------------------------------------------------------------------------------
function fun_bp(ce::CE_Economy_PInf, bp_v::Float64, π::Float64, b_v::Float64, y_v::Float64, B_v::Float64, q::Float64, Expec::Float64)
    c_v = max(y_v - b_v* ((1-ce.mb)*ce.zb + ce.mb) - B_v*(1+π) + q*(bp_v-(1-ce.mb)*b_v), 1e-14)
    V_v = -u_fun(ce, c_v) - ce.β*Expec
return V_v
end
#------------------------------------------------------------------------------


#----------------------------------------------------------------------------------
#Markov Transition Fx
#----------------------------------------------------------------------------------
function Markov_Switch_fx(ce::CE_Economy_PInf, z_hat::Float64)
zprime = z_hat * ce.ΠT[1,1] + (1.0-z_hat) * ce.ΠT[2,1];  # Exogenous Markov transision
return zprime
end
#----------------------------------------------------------------------------------


#------------------------------------------------------------------------------
# Functions for Yields [quarterly] & Spreads [annualized]
#------------------------------------------------------------------------------
function Yield_fx(ce::CE_Economy_PInf,Price::Float64)    # Quarterly Yield
yield   = 1./Price .* (ce.mb + (1-ce.mb)*ce.zb) - ce.mb
return yield
end
function Spreads_fx(ce::CE_Economy_PInf,Price::Float64)   # Annualized Spreads
yield   = Yield_fx(ce,Price)
spread  = ( (1+yield)./(1+ce.r) ).^4   -1
spread  = spread*100
return spread
end
#------------------------------------------------------------------------------


#----------------------------------------------------------------------------------
function tauchen_fun(ny::Int64, ρ::Float64, σe::Float64; m=3, mu=0.0)
#----------------------------------------------------------------------------------
    σy = σe/sqrt((1-ρ^2))
    λ1 = -m*σy; λn = m*σy
    λgrid = linspace(λ1,λn,ny)
    ww = λgrid[2] - λgrid[1]
    distrib = Normal(0,1)
    Π = Array{Float64}(ny,ny)
    for ii=1:ny
        Π[ii,1] = cdf(distrib,(λ1+ww/2-(1-ρ)*mu-ρ*λgrid[ii])/σe) # For j=1
        Π[ii,end] = 1.0-cdf(distrib,(λn-ww/2-(1-ρ)*mu-ρ*λgrid[ii])/σe) # For j=ny
        for jj=2:ny-1
            Π[ii,jj] = cdf(distrib,(λgrid[jj]+ww/2-(1-ρ)*mu-ρ*λgrid[ii])/σe) - cdf(distrib,(λgrid[jj]-ww/2-(1-ρ)*mu-ρ*λgrid[ii])/σe)
        end
    end
    return λgrid,Π
end
#----------------------------------------------------------------------------------

